<?php

namespace App\Http\Controllers\Admin;

use App\Http\Repository\AdminRepository;
use App\Http\Repository\AreaRepository;
use App\Http\Repository\ChunkRepository;
use App\Http\Repository\GaterRepository;
use App\Http\Repository\MessageRepository;
use App\Http\Repository\PageViewRepository;
use App\Http\Repository\SetRepository;
use App\Http\Repository\VersionRepository;
use App\Http\Servers\Admin\ImageServer;
use App\Http\Servers\Admin\IndexServer;
use App\Http\Servers\Admin\BaseServer;
use Faker\Provider\Image;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class IndexController extends CommonController
{
    //后台首页
    public function index(Request $request, BaseServer $baseServer, ChunkRepository $chunkRepository, PageViewRepository $pageViewRepository, MessageRepository $messageRepository)
    {
        $data['chunksPageViewNum'] = $chunkRepository->getPageViewNumByChunk();

        $data['allPageViewNum'] = $baseServer->getAllPageViewNum();

        $data['col'] = (int)floor(12 / (count($data['chunksPageViewNum']) + 1));

        $data['pageView'] = $pageViewRepository->getPageViewGroupMouth();

        $data['map'] = $baseServer->getMapInfos();

        $data['source'] = $baseServer->getSources();

        $data['create'] = $chunkRepository->getEveryChunkEveryMouthCreateNum();
        $data['create']['留言评价'] = $messageRepository->getMessageEveryMonth();

        $data['todayViewNum'] = \App\PageView::where('created_at', 'like', date('Y-m-d' . '%'))
            ->where('ip', '<>', '127.0.0.1')
            ->count();

        $data['pageViewGroupArea'] = $pageViewRepository->getPageViewGroupArea();

        $data['allDayViewNum'] = \App\PageView::where('ip', '<>', '127.0.0.1')->count();

        return view('admin.index.index', $data);
    }

    //版本信息
    public function versions(Request $request, VersionRepository $versionRepository)
    {
        if ($request->has('del')) {
            $version = \App\Version::find($request->del);
            $result = $version->delete();
            if ($result) {
                $message['message'] = message(true, '删除成功', $version->version . ' 版本删除成功!');
            } else {
                $message['message'] = message(true, '删除失败', $version->version . ' 版本删除失败!');
            }
            return back()->with($message);
        }

        $data['versions'] = $versionRepository->getVersions();
        return view('admin.index.versions', $data);
    }

    //版本信息添加
    public function versions_add(Request $request, VersionRepository $versionRepository)
    {
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'version' => 'required|unique:versions',
                'title' => 'required',
                'describe' => 'required',
            ]);

            $create['version'] = $request->version;
            $create['title'] = $request->title;
            $create['describe'] = $request->describe;

            $result = \App\Version::create($create);
            if ($result) {
                $message['message'] = message(true, '添加成功', $result->version . ' 版本添加成功!');
            } else {
                $message['message'] = message(false, '添加失败', $result->version . ' 版本添加失败!');
            }
            return back()->with($message);
        }

        //得到最新的一个版本号
        $data['version'] = $versionRepository->getNewVersion();

        return view('admin.index.versions_add', $data);
    }

    //版本信息编辑
    public function versions_edit(Request $request)
    {
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'id' => 'required',
                'version' => 'required|unique:versions,version,' . $request->id . ',id',
                'title' => 'required',
                'describe' => 'required',
            ]);

            $update['version'] = $request->version;
            $update['title'] = $request->title;
            $update['describe'] = $request->describe;

            $result = \App\Version::where('id', $request->id)->update($update);
            if ($result) {
                $message['message'] = message(true, '编辑成功', $request->version . ' 版本编辑成功!');
            } else {
                $message['message'] = message(false, '编辑失败', $request->version . ' 版本编辑失败!');
            }
            return back()->with($message);
        }

        //得到当前版本信息
        $data['version'] = \App\Version::findorfail($request->id);

        return view('admin.index.versions_edit', $data);
    }

    //配置信息
    public function set(Request $request, AreaRepository $areaRepository, BaseServer $baseServer, IndexServer $indexServer)
    {
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'web_name' => 'required',
                'web_url' => 'required|url',
                'web_title' => 'required',
//                'web_keywords' => 'required|min:3|max:255',
                'web_description' => 'required|min:3|max:255',
//                'web_keywords_long' => 'required|min:3|max:255',
                'web_email' => 'email',
                'web_phone' => 'required',
            ]);
            $result = $indexServer->set($request);
            if ($result) {
                $message['message'] = message(true, '设置成功', '配置信息设置成功!');
                $baseServer->resetTagForInfo($request->input('web_keywords'));
            } else {
                $message['message'] = message(false, '设置失败', '配置信息设置失败!');
            }
            return back()->with($message);
        }

        $data['wap_theme'] = glob('resources/views/home/m/*');

        config(['web_logo' => \App\Image::where('id', config('set.web_logo'))->value('path')]);
        config(['web_qrcode' => \App\Image::where('id', config('set.web_qrcode'))->value('path')]);

        $data['areas'] = $areaRepository->getAreasByLv();

        return view('admin.index.set', $data);
    }

    //管理员列表
    public function admin(Request $request, AdminRepository $adminRepository)
    {
        if ($request->has('del')) {
            $admin = \App\Admin::findorfail($request->del);
            $result = $adminRepository->delAdminById($request->del);

            if ($result) {
                $message['message'] = message(true, '删除成功', '管理员 ' . $admin->name . ' 删除成功!');
            } else {
                $message['message'] = message(true, '删除成功', '管理员 ' . $admin->name . ' 删除成功!');
            }
            return back()->with($message);
        }

        $data['admins'] = \App\Admin::select('id', 'name', 'email', 'is_root', 'status', 'login_at')
            ->get();

        return view('admin.index.admin', $data);
    }

//管理员添加
    public function admin_add(Request $request, GaterRepository $gaterRepository, AdminRepository $adminRepository)
    {
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'name' => 'required|unique:admins',
                'email' => 'required|email|unique:admins',
                'password' => 'required',
                'gater' => 'required|array',
            ]);

            $create['name'] = $request->name;
            $create['email'] = $request->email;
            $create['password'] = bcrypt($request->password);
            $create['status'] = 1;
            $create['is_root'] = 0;

            $result = \App\Admin::create($create);
            if ($result) {
                $adminRepository->reGater($result->id, $request->gater, false);

                $message['message'] = message(true, '添加成功', '添加管理员' . $request->name . '成功!');
            } else {
                $message['message'] = message(false, '添加失败', '添加管理员' . $request->name . '失败!');
            }

            return back()->with($message);
        }

        //得到权限分组
        $data['gaters'] = $gaterRepository->getGroupGater();
        return view('admin.index.admin_add', $data);
    }

    //管理员编辑
    public function admin_edit(Request $request, GaterRepository $gaterRepository, AdminRepository $adminRepository)
    {
        if ($request->isMethod('post')) {
            if (!(bool)\Auth::guard('admin')->user()->is_root) {
                $message['message'] = message(false, '修改失败', '不是超级管理员,无法修改管理员信息!');
                return back()->with($message);
            }

            $this->validate($request, [
                'id' => 'required',
                'name' => 'required|unique:admins,name,' . $request->id . ',id',
                'email' => 'required|email|unique:admins,email,' . $request->id . ',id',
                'password' => '',
                'gater' => 'required|array',
            ]);

            $request->has('password') && $update['password'] = bcrypt($request->password);
            $update['name'] = $request->name;
            $update['email'] = $request->email;
            $update['status'] = $request->has('status') ? 1 : 0;

            $result = \App\Admin::where('id', $request->id)->update($update);
            if ($result) {
                $adminRepository->reGater($request->id, $request->gater, true);

                $message['message'] = message(true, '修改成功', '管理员 ' . $request->name . ' 信息修改成功!');
            } else {
                $message['message'] = message(false, '修改失败', '管理员 ' . $request->name . ' 信息修改失败!');
            }
            return back()->with($message);
        }

        //得到权限分组
        $data['gaters'] = $gaterRepository->getGroupGater();

        //得到管理员信息
        $data['admin'] = $adminRepository->getAdminById($request->id);

        return view('admin.index.admin_edit', $data);
    }

    //地区管理
    public function area(Request $request, AreaRepository $areaRepository)
    {
        if ($request->has('del')) {
            $childCount = \App\Area::where('parent', $request->del)->count();
            if ((bool)$childCount) {
                $message['message'] = message(false, '删除失败', '该地区之下还存在其他地区,无法删除!');
                return back()->with($message);
            }
            $area = \App\Area::find($request->del);
            $result = $area->delete();

            if ($result) {
                $message['message'] = message(true, '删除成功', $area->name . ' 地区删除成功!');
            } else {
                $message['message'] = message(false, '删除失败', $area->name . ' 地区删除失败!');
            }
            return back()->with($message);
        }

        $data['area'] = $areaRepository->getAreasByX();

        return view('admin.index.area', $data);
    }

//地区添加
    public
    function area_add(Request $request, AreaRepository $areaRepository)
    {
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'name' => 'required',
                'domain' => 'required|alpha_dash|unique:areas',
                'parent' => 'required',
            ]);

            $create['name'] = $request->name;
            $create['domain'] = $request->domain;
            $create['parent'] = $request->parent;
            $pathprefix = \App\Area::where('id', $request->parent)->value('path');
            $create['path'] = $pathprefix . $create['parent'] . ',';
            $create['status'] = $request->has('status') ? 1 : 0;

            $result = \App\Area::create($create);
            if ($result) {
                $message['message'] = message(true, '添加成功', '地区 ' . $request->name . ' 添加成功!');
            } else {
                $message['message'] = message(false, '添加失败', '地区 ' . $request->name . ' 添加失败!');
            }
            return back()->with($message);
        }

        $data['areas'] = $areaRepository->getAreasByLv();

        return view('admin.index.area_add', $data);
    }

    //地区编辑
    public function area_edit(Request $request, AreaRepository $areaRepository)
    {
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'id' => 'required',
                'name' => 'required',
                'domain' => 'required|alpha_dash|unique:areas,domain,' . $request->id . ',id',
                'parent' => 'required',
            ]);

            $update['name'] = $request->name;
            $update['domain'] = $request->domain;
            $update['parent'] = $request->parent;
            $pathprefix = \App\Area::where('id', $request->parent)->value('path');
            $update['path'] = $pathprefix . $update['parent'] . ',';
            $update['status'] = $request->has('status') ? 1 : 0;

            $result = \App\Area::where('id', $request->id)->update($update);
            if ($result) {
                $message['message'] = message(true, '编辑成功', '地区 ' . $request->name . ' 编辑成功!');
            } else {
                $message['message'] = message(false, '编辑失败', '地区 ' . $request->name . ' 编辑失败!');
            }
            return back()->with($message);
        }

        $data['area'] = \App\Area::findorfail($request->id);

        $data['areas'] = $areaRepository->getAreasByLv();

        return view('admin.index.area_edit', $data);
    }

    //帮助中心
    public function help(Request $request)
    {
        if ($request->has('del')) {
            $help = \App\Help::findorfail($request->del);
            $result = $help->delete();
            if ($result) {
                $message['message'] = message(true, '删除成功', '帮助信息 ' . $request->name . ' 删除成功!');
            } else {
                $message['message'] = message(false, '删除失败', '帮助信息 ' . $request->name . ' 删除失败!');
            }
            return back()->with($message);
        }

        $data['helps'] = \App\Help::orderBy('xindex', 'DESC')->get();

        return view('admin.index.help', $data);
    }

    //帮助中心信息添加
    public function help_add(Request $request)
    {
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'name' => 'required',
                'tag' => 'required',
                'xindex' => 'required',
                'describe' => 'required',
            ]);

            $create['name'] = $request->name;
            $create['tag'] = $request->tag;
            $create['xindex'] = $request->xindex;
            $create['describe'] = $request->describe;

            $result = \App\Help::create($create);
            if ($result) {
                $message['message'] = message(true, '添加成功', '帮助信息 ' . $request->name . ' 添加成功!');
            } else {
                $message['message'] = message(false, '添加失败', '帮助信息 ' . $request->name . ' 添加失败!');
            }
            return back()->with($message);
        }

        $tmpTag = explode(',', config('set.web_keywords'));
        shuffle($tmpTag);
        $data['tag'] = $tmpTag[0];

        return view('admin.index.help_add', $data);
    }

    //帮助中心信息编辑
    public function help_edit(Request $request)
    {
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'id' => 'required',
                'name' => 'required',
                'tag' => 'required',
                'xindex' => 'required',
                'describe' => 'required',
            ]);

            $update['name'] = $request->name;
            $update['tag'] = $request->tag;
            $update['xindex'] = $request->xindex;
            $update['describe'] = $request->describe;

            $result = \App\Help::where('id', $request->id)->update($update);
            if ($result) {
                $message['message'] = message(true, '编辑成功', '帮助信息 ' . $request->name . ' 编辑成功!');
            } else {
                $message['message'] = message(false, '编辑失败', '帮助信息 ' . $request->name . ' 编辑失败!');
            }
            return back()->with($message);
        }

        $data['help'] = \App\Help::findorfail($request->id);

        return view('admin.index.help_edit', $data);
    }

    //操作记录
    public function operate()
    {
        $data['operates'] = \App\Operate::join('admins', 'admins.id', '=', 'operates.admin')
            ->select('operates.*', 'admins.name as admin')
            ->orderBy('created_at', 'DESC')
            ->get();
        foreach ($data['operates'] as $k => $operate) {
            $data['operates'][$k]['parameter'] = json_decode($operate['parameter'], true);
        }
        return view('admin.index.operate', $data);
    }

    //意见反馈
    public function opinion(Request $request)
    {
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'email' => 'required|email',
                'title' => 'required',
                'describe' => 'required',
            ]);

            $data = [
                'email' => config('mail.from.address'),
                'name' => config('set.web_name'),
                'ip' => getIp(),
                'admin_id' => \Auth::guard('admin')->user()->id,
                'admin_id' => \Auth::guard('admin')->user()->name,
                'time' => date('Y-m-d H:i:s'),
                'content' => $request->describe,
                'title' => '[' . config('set.web_name') . ']' . $request->title,
                'reply_email' => $request->email
            ];

            $result = \Mail::send('admin.emails.opinion', $data, function ($message) use ($data) {
                $message->to($data['email'], $data['name'])->subject($data['title']);
            });

            if ($result) {
                $message['message'] = message(true, '提交成功', '您的意见我们已收到,我们会尽快回复!');
            } else {
                $message['message'] = message(false, '提交失败', '抱歉,邮件发送失败!');
            }
            return back()->with($message);
        }

        return view('admin.index.opinion');
    }
}
